package net.borlis.sample.service.repositories.common;

import net.borlis.sample.service.entities.common.AuditedEntity;
import org.hibernate.envers.AuditReader;
import org.hibernate.envers.AuditReaderFactory;

import java.util.Date;

/**
 * Created by alexander.borlis on 18.06.2014.
 */
public abstract class AuditRepository<T extends AuditedEntity> extends DynamixRepository<T> implements IAuditRepository<T> {

    @Override
    public Long getCurrentRevision() {
        final AuditReader reader = AuditReaderFactory.get(getEm());
        return reader.getRevisionNumberForDate(new Date(Long.MAX_VALUE)).longValue() - 1;
    }

    @Override
    public void revertEntityRevision(T t, Long revision) {
        T preT = findByRevision(t, revision);
        if (preT != null) {
            update(preT);
        }
    }

    @Override
    public T findByRevision(T t, Long revision) {
        final AuditReader reader = AuditReaderFactory.get(getEm());
        return reader.find(getEntityClass(), t.getId(), revision.intValue());
    }

    @Override
    public boolean checkExistingRevision(T t, Long revision) {
        final AuditReader reader = AuditReaderFactory.get(getEm());
        return reader.getRevisions(getEntityClass(), t.getId()).contains(revision.intValue());
    }
}
